import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant';
import i18n from "@/i18n";
import { BASE_URL } from "@/config";
import router from '@/router/router'
import { getStorage } from '@/utils/utis'
import { signatureGenerate } from "@/utils/signatureUtil"
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let baseUrl = BASE_URL
if (getStorage('tzlj')) {
  baseUrl = getStorage('tzlj');
}

// 创建
const request = axios.create({
  baseURL: baseUrl,
  timeout: 8000, // 超时时间
  //   withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
  //   transformRequest: [function(data) {
  //     return data
  //   }]
})
// 拦截请求
request.interceptors.request.use(config => {
  if (config.loading) {
    Toast.loading({ duration: 0, forbidClick: true })
  }
  //if (store?.state?.user?.userInfo?.token) {
  if (store.state.user.userInfo.token != undefined && store.state.user.userInfo.token !== '') {
    // config.headers.Authorization = store.state.token
    if (!config.params) { // 放在哪里
      config.params = {}
    }
    config.params['token'] = store.state.user.userInfo.token
  }
  // 获取请求头参数
  const { timestamp, signature } = signatureGenerate()
  if (timestamp) config.headers['tissuePaper'] = timestamp;
  if (signature) config.headers['sign'] = signature;
  return config
}, error => {
  Promise.reject(error)
})

/**
 * 烤猫, [7/27/2022 9:08 PM]
 * 0 成功
1 直接显示
105 直接提示“当前还需交易“ + 返回的金额值 + ”,才可提币"
401 是需要实名认证，问客户”未实名认证，是否认证？"
403 无登录信息，跳转登录页面
506 "帐户异常需要进行C3认证，请联系在线客服。"
 */

// 拦截响应
request.interceptors.response.use(res => { // 200开头的
  if (res.config.loading) {
    Toast.clear()
  }

  // console.log(res);
  const { code, data, msg } = res.data

  switch (code / 1) {
    case 0:
      return Promise.resolve(data)
    case 403:
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
      store.commit('user/SET_OUT');
      return Promise.reject('reject')
    // break;
    default:
      if (msg != undefined) {
        Toast.fail({
          // icon: 'none',
          message: i18n.t(msg)
        });
      }
      //console.log('错误')
      return Promise.reject(res.data)
  }
}, error => {
  if (error.code == 'ERR_NETWORK') {
    Toast({ message: 'ERR_NETWORK', type: 'fail', duration: 1000 })
  } else if (error.code == 'ECONNABORTED') {
    //Toast({ message: 'Network Timeout', type: 'fail', duration: 2000 })
    return Promise.reject(error);
  } else if (error && error.response) {
    //console.log(error.response);
    switch (error.response.status) {
      case 400: error.message = i18n.t('请求错误'); break
      case 401: error.message = i18n.t('未授权，请登录'); break
      case 403: error.message = i18n.t('拒绝访问'); break
      case 404: error.message = i18n.t(`请求地址不存在: ${error.response.config.url}`); break
      case 408: error.message = i18n.t('请求超时'); break
      case 500: error.message = i18n.t('服务器内部错误'); break
      case 501: error.message = i18n.t('服务未实现'); break
      case 502: error.message = i18n.t('网关错误'); break
      case 503: error.message = i18n.t('服务不可用'); break
      case 504: error.message = i18n.t('网关超时'); break
      case 505: error.message = i18n.t('HTTP版本不受支持'); break
      default: error.message = i18n.t('未捕获到的状态码'); break
    }
  }
  // eslint-disable-next-line prefer-promise-reject-errors
  return Promise.reject(error);
}
)
export default request
